﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Demo.Api.Data;
using Demo.Api.Entities;
using Microsoft.EntityFrameworkCore;

namespace Demo.Api.Services
{
    public class ReverseClearLineAndNodeRepository
    {
        protected readonly DemoDbContext Context;
        protected DbSet<ReverseClearLineAndNodeDo> DataSet;

        public ReverseClearLineAndNodeRepository(DemoDbContext context)
        {
            Context = context ?? throw new ArgumentNullException(nameof(context));
            DataSet = Context.ReverseClearLineAndNodes;
        }

        public virtual async Task<IEnumerable<ReverseClearLineAndNodeDo>> GetsAsync(long flowChartId)
        {
            return await DataSet.Where(x => x.FlowChartId == flowChartId).ToListAsync();
        }


        public virtual async Task<bool> Add(ReverseClearLineAndNodeDo data)
        {
            if (data == null)
                throw new ArgumentNullException(nameof(data));
            if (data.FlowChartId == 0)
                throw new ArgumentException($"{nameof(data.FlowChartId)}不能为零");
            if (data.LineId == 0)
                throw new ArgumentException($"{nameof(data.LineId)}不能为零");
            if (data.NodeId == 0)
                throw new ArgumentException($"{nameof(data.NodeId)}不能为零");
            await DataSet.AddAsync(data);
            return await Context.SaveChangesAsync() > 0;
        }


        public virtual async Task<bool> Delete(long id)
        {
            var temp = await DataSet.FirstOrDefaultAsync(x => x.Id == id);
            if (temp != null)
            {
                DataSet.Remove(temp);
                return await Context.SaveChangesAsync() >= 0;
            }
            throw new CustomException("数据不存在");
        }
    }
}